/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.common.tcc.reflect;

import com.google.common.base.Optional;
import yhao.infra.web.common.tcc.TccCommandAction;
import yhao.infra.web.common.tcc.TccCommandHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import yhao.infra.apilist.RequestResult;
import yhao.infra.apilist.tcc.TccFeign;
import yhao.infra.common.InfraCommonConstants;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * tcc代理类处理类
 *
 * @author yoara
 */
public class TccFeignHandler implements InvocationHandler {
    private Logger logger = LoggerFactory.getLogger(InfraCommonConstants.TCC_FEIGN_LOGGER);
    private InvocationHandler delegate;

    @Override
    public RequestResult invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if(TccCommandHolder.tccEnabled()){
            Method fallback = getFallbackMethod(proxy.getClass(),method);
            if(fallback!=null){
                logger.info(makeMsg("[add fallback]"+method.getName())+"[:]"+fallback.getName());
                TccCommandHolder.addTccCommandAction(new TccCommandAction(method.getName(),()->{
                    try {
                        return (RequestResult)fallback.invoke(proxy,args);
                    } catch (Exception e) {
                        logger.error(makeMsg(e.getMessage()));
                        throw e;
                    }
                }));
            }else{
                logger.info(makeMsg("[no fallback]"+method.getName()));
            }
        }
        return (RequestResult)this.delegate.invoke(proxy, method, args);
    }

    private Method getFallbackMethod(Class<?> type,Method method){
        TccFeign tccFeign = method.getAnnotation(TccFeign.class);
        if (tccFeign!=null&&StringUtils.isNotBlank(tccFeign.fallbackMethod())) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            Optional<Method> fMethod = getMethod(type, tccFeign.fallbackMethod(),parameterTypes);
            return fMethod.orNull();
        }
        return null;
    }

    private Optional<Method> getMethod(Class<?> type, String name, Class<?>... parameterTypes) {
        Method[] methods = type.getDeclaredMethods();
        for (Method method : methods) {
            if (method.getName().equals(name) && Arrays.equals(method.getParameterTypes(), parameterTypes)) {
                return Optional.of(method);
            }
        }
        Class<?> superClass = type.getSuperclass();
        if (superClass != null && !superClass.equals(Object.class)) {
            return getMethod(superClass, name, parameterTypes);
        } else {
            return Optional.absent();
        }
    }

    private String makeMsg(String originalMsg){
        return "[handler:]"+originalMsg;
    }

    public void setDelegate(InvocationHandler delegate) {
        this.delegate = delegate;
    }
}
